package sockets;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server
{
    public static void main(String[] args)
    {
	Socket socket = null;
	int sum = 0;
	String sumString = "";

	while (true)
	{
	    try
	    {
		ServerSocket serverSocket = new ServerSocket(250);

		System.out.println("Waiting client conection.");

		socket = serverSocket.accept();
		DataOutputStream outputStream = new DataOutputStream(
			socket.getOutputStream());
		DataInputStream inputStream = new DataInputStream(
			socket.getInputStream());

		while (true)
		{
		    String myOperation = inputStream.readUTF();

		    if (myOperation.equals("Increasing"))
		    {
			sumString = String.valueOf(++sum);
		    }
		    else if (myOperation.equals("set_sum"))
		    {
			sum = 0;
			sumString = String.valueOf(sum);
			System.out.println("Counter = " + sumString);
		    }
		    outputStream.writeUTF(sumString);
		    outputStream.flush();
		}
	    }
	    catch (Exception e)
	    {
		System.err.println("Closing connection.");
		if (socket != null)
		{
		    try
		    {
			socket.close();
		    }
		    catch (IOException ex)
		    {}
		}
	    }
	}
    }
}
